package com.hxd.mall.module.account.login

import android.graphics.Color
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectActivity
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.login_bind_view
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.login_or_register_phone_num
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.login_or_register_type
import com.hxd.mall.constant.HxdConstants.WX_PackageName
import com.hxd.mall.constant.HxdConstants.from_login_to_verifyCode
import com.hxd.mall.constant.HxdConstantsAccount.wx_login_flag
import com.hxd.mall.constant.HxdConstantsRouterPath.PathAccount.path_login_input_phone
import com.hxd.mall.constant.HxdConstantsRouterPath.PathAccount.path_register
import com.hxd.mall.constant.HxdConstantsRouterPath.PathAccount.path_verify_code
import com.hxd.mall.module.account.bean.ServiceFlag
import com.hxd.mall.utils.local.*
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.ThirdInitUtil.unBindJPush
import com.hxd.mall.utils.open.ToastUtil
import com.hxd.mall.utils.open.addSetOnClickListener
import com.hxd.threelibrary.baichuan.ShoppingUtils.checkPackage
import com.hxd.threelibrary.weChat.WeChatUtils
import kotlinx.android.synthetic.main.activity_login_input_phone_number.*
import java.util.regex.Pattern

/**
 * 登录(输入手机号)
 */
@Route(path = path_login_input_phone)
class LoginActivity : BaseInjectActivity<ILoginPresenter>(), ILoginView {
    /**
     * 用来区分当前界面是登录还是绑定手机号界面
     *  1 登录 --- 默认
     * 其他值 绑定手机号，其他方式为登录
     */

    private var mCurrentType = 1

    override fun attachLayoutRes(): Int = R.layout.activity_login_input_phone_number

    override fun initViews() {
        setTitleCommon()
        // login btn
        addViewClick()

        //解绑极光推送
        unBindJPush()
    }

    override fun loadData(vararg data: Any) {
    }

    /**
     * 错误提示
     */
    override fun showTipMessage(message: String, type: Int) {

    }

    override fun initData() {
        mCurrentType = intent.getIntExtra(login_bind_view, 1)
        sendPoint(tel_input_page_view)
        whichView()
    }

    /**
     * 界面展示布局
     */
    private fun whichView() {
        if (mCurrentType == 1) {
            //登录界面
            tv_bindphone.visibility = View.GONE
            login_icon.visibility = View.VISIBLE
            if (checkPackage(this, WX_PackageName)) {
                //如果安装了 微信就显示微信登录入口
                tv_wx_login.visibility = View.VISIBLE
            } else {
                tv_wx_login.visibility = View.GONE
            }
        } else {
            //绑定界面
            tv_bindphone.visibility = View.VISIBLE
            login_icon.visibility = View.GONE
            tv_wx_login.visibility = View.GONE
        }
    }

    override fun isRegister(register: Boolean?) {
        if (null != register && register) {
            //如果注册了 跳转到验证码界面
            routerNavigation(
                path_verify_code, hashMapOf(
                    login_or_register_phone_num to inputPhone.getInputContent(),
                    login_or_register_type to from_login_to_verifyCode,
                    login_bind_view to mCurrentType
                )
            )
        } else {
            //没有注册了 跳转到注册界面
            routerNavigation(
                path_register,
                hashMapOf(
                    login_or_register_phone_num to inputPhone.getInputContent(),
                    login_bind_view to mCurrentType
                )
            )
        }
    }

    override fun fetchFlag(t: ServiceFlag?) {
        if (null == t) return
        //从微信获取code,然后把code值传递给后端进行请求
        t.data?.state?.let { HxdSharePreferenceUtil.saveStringData(wx_login_flag, it) }
        WeChatUtils().regToWx(this, t?.data?.scope, t?.data?.state)
    }

    private fun addViewClick() {
        inputPhone.inputFinish { finish ->
            if (finish) {
                next.isClickable = true
                layout_next.setBackgroundResource(R.drawable.shape_btn_disable_bg)
                next.setBackgroundColor(0)
            } else {
                next.isClickable = false
                layout_next.setBackgroundResource(R.drawable.shape_btn_disable_bg)
                next.setBackgroundColor(Color.parseColor("#55ffffff"))
            }
        }

        addSetOnClickListener(next, inputPhone, tv_wx_login) {
            when (it) {
                next -> {
                    val content = inputPhone.getInputContent()

                    if (TextUtils.isEmpty(content) || content.length < 11 ||
                        content.startsWith("10") || content.startsWith("11") || content.startsWith("12") ||
                        !Pattern.compile("([0-9])*").matcher(content).matches()
                    ) {
                        ToastUtil.showToast("请输入正确的手机号")
                        return@addSetOnClickListener
                    }
                    mPresenter?.isRegistered(inputPhone.getInputContent(),mCurrentType)

                    sendPoint(tel_input_page_next_button_click)
                }
                tv_wx_login -> {
                    //微信授权
                    sendPoint(wechat_log_in__button_click)
                    mPresenter?.getflag()
                }
                inputPhone -> sendPoint(tel_input_box_click)
            }

        }
        //设置了setOnClickListener后，强制clickable为true,xml中的false失效，需要在代码中设置
        next.isClickable = false
    }

    private fun isPhoneNum(mobileNums: String): Boolean {
        // "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        val telRegex = "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}$"
        return if (TextUtils.isEmpty(mobileNums))
            false
        else
            return Pattern.matches(telRegex, mobileNums)
    }
}